#include "ImageProcessor.h"
#include "camera.h"
#include "cameraeth0.h"
#include "camerausb.h"
#include "configmanager.h"
#include "configmodel.h"
#include "logger.h"
#include "source/aiprocess.h"
#include "source/ngtable.h"
#include "source/tools.h"
#include "source/yolodetector.h"
#include "source/wifiscanner.h"
#include "configadapter.h"
#include "systemmonitor.h"
#include "filedeleter.h"
#include "popupmanager.h"
#include "errordialogmanager.h"
#include "cvalgedgedetection.h"
#include "detectcachemodel.h"
#include "afterdetect.h"
#include "chartplotter.h"
#include "defectstatistics.h"
#include "networkmanager.h"
#include "floorserial.h"
#include "floorsetting.h"
#include "gpiocontroller.h"
#include "filereader.h"
#include "fileoperations.h"
#include "gitupdaterqml.h"
#include "screenShot.h"
#include "authorizationtiming.h"
#include "remotecontrol.h"
#include "testrt.h"
#include "faultcachemodel.h"
#include "imagesavemanager.h"
#include "logReader.h"
#include "mousetracker.h"
#include "pccore.h"
#include "kcentergreedyint8.h"
#include "pccoremodel.h"
// #include <QGuiApplication>
#include <QApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QStringList>
int testHiconVMS();



int main(int argc, char *argv[])
{
    // cpu_set_t cpuset;
    // CPU_ZERO(&cpuset);
    // CPU_SET(1, &cpuset); // 将主线程绑定到 CPU 1
    //一定要放QApplication阿
    qputenv("QT_IM_MODULE", QByteArray("qtvirtualkeyboard"));

    QApplication app(argc, argv);
    //QGuiApplication::setOverrideCursor(Qt::BlankCursor);
    QResource::registerResource("/home/ASuser/master/bin/skin/helper.rcc");
    QResource::registerResource("/home/ASuser/master/bin/skin/image.rcc");

#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
#endif

    //qmlRegisterSingletonType<ChartPlotter>("Charts", 1, 0, "ChartPlotter", ChartPlotter::qmlInstance);
    //wifi

    ChartPlotter::getInstance();
    //qmlRegisterType<WiFiScanner>("CustomComponents", 1, 0, "WiFiScanner");

    testLogger();
    LogDebug << "get start";
    bool isRestart = false;
    for (int i = 1; i < argc; ++i) {
        LogDebug << "get start" <<QString(argv[i]);
        if (QString(argv[i]) == "--restart") {
            isRestart = true;
            break;
        }
    }

    // LogDebug << getMacAddress12Chars("eth0");
    // QThread::sleep(2);
    // NetworkManager::instance()->downloadUpdate();
    // while (1) {
    //     QThread::sleep(1);
    // }

    // testAIprocess();
    // return app.exec();

    // testYoloDetector();
    // return app.exec();

    //testParametertable();
    testNgTable();
    QQmlApplicationEngine engine;


    // 将执行目录传递给 QML
    QString currentPath = QDir::currentPath();
    LogInfo << "-----------WorkPath[" << currentPath << "]----------------";
    engine.rootContext()->setContextProperty("currentPath", currentPath);

    //log日志
    engine.rootContext()->setContextProperty("logger", &Logger::getInstance());

    engine.addImageProvider(QLatin1String("imageProvider"), &ImageProvider::getInstance());
    ImageProcessor::getInstance(&ImageProvider::getInstance());
    QStringList categories = {"camera","preprocessing","yoloDetection","cvInspection","gpioModule","light","summary","networkUpdate"};
    categories.insert(0, "base");
    AfterDetect::getInstance();
    //engine.rootContext()->setContextProperty("afterDetect", &);
    engine.rootContext()->setContextProperty("NetworkManager", NetworkManager::instance());
    //engine.rootContext()->setContextProperty("camera", &CameraEth0::getInstance());
    engine.rootContext()->setContextProperty("preprocessor", &PreProcessor::getInstance());
    engine.rootContext()->setContextProperty("camera", &CameraEth0::getInstance());
    engine.rootContext()->setContextProperty("configmanager", &ConfigManager::getInstance());
    engine.rootContext()->setContextProperty("cacheModel", &DetectCacheModel::instance());
    engine.rootContext()->setContextProperty("faultCacheModel",&FaultCacheModel::instance());


    //参数表导入
    ConfigAdapter *configAdapter = new ConfigAdapter();
    engine.rootContext()->setContextProperty("configAdapter", configAdapter);
    //系统监控
    SystemMonitor *systemMonitor = new SystemMonitor();
    engine.rootContext()->setContextProperty("systemMonitor", systemMonitor);
    engine.rootContext()->setContextProperty("precisionIdentify", &PrecisionIdentify::getInstance());
    //Camera::getinstance();
    engine.rootContext()->setContextProperty("CvAlgEdgeDetection", &CvAlgEdgeDetection::getInstance());
    engine.rootContext()->setContextProperty("AIprocess", &AIprocess::getInstance());
    engine.rootContext()->setContextProperty("imageProcessor", &ImageProcessor::getInstance());
    engine.rootContext()->setContextProperty("imageProvider", &ImageProvider::getInstance());
    engine.rootContext()->setContextProperty("popupManager", &PopupManager::instance());
    engine.rootContext()->setContextProperty("errorDialogManager", &ErrorDialogManager::instance());
    //wifi
    engine.rootContext()->setContextProperty("wifiScanner", &WiFiScanner::getInstance());
    //绘图
    DefectStatistics& defectStatistics = DefectStatistics::instance();
    engine.rootContext()->setContextProperty("defectStats", &defectStatistics);
    //字符保存
    engine.rootContext()->setContextProperty("imageSaveManager",&ImageSaveManager::getInstance());
    //底层连接
    engine.rootContext()->setContextProperty("floorSetting",&FloorSetting::getInstance());
    //串口
    engine.rootContext()->setContextProperty("gpioController",&GpioController::getInstance());
    //更新
    engine.rootContext()->setContextProperty("gitUpdaterQML",&gitUpdaterQML::instance());
    //u盘检测
    FileReader flieReader;
    engine.rootContext()->setContextProperty("fileReader",&flieReader);

    //远程更新
    RemoteControl remoteControl;
    engine.rootContext()->setContextProperty("remoteControl",&remoteControl);

    //导出
    FileOperations fileOperations;
    engine.rootContext()->setContextProperty("fileOperations", &fileOperations);

    engine.rootContext()->setContextProperty("pCcore", &PCcore::getInstance());
    engine.rootContext()->setContextProperty("kCenterGreedyInt8", &KCenterGreedyInt8::instance());
    engine.rootContext()->setContextProperty("pCcoreModel", &PCcoreModel::instance());


    //倒计时
    AuthorizationTiming authorizationTiming;
    engine.rootContext()->setContextProperty("authorizationTiming", &authorizationTiming);
    //imageProcessor.startTriggerLoop();
    for (const QString &category : categories) {
        ConfigModel* model = new ConfigModel();
        model->loadData(category);  // 假设 ConfigModel 有一个加载数据的方法
        engine.rootContext()->setContextProperty(category + "Model", model);
    }
    engine.rootContext()->setContextProperty("categoriesButton", QVariant::fromValue(categories));
    engine.rootContext()->setContextProperty("mouseTracker", &MouseTracker::getInstance());

    //U盘相关
    // FileDeleter fileDeleter;
    engine.rootContext()->setContextProperty("fileDeleter", &FileDeleter::getInstance());
    // FileDeleter fileDeleter;
    // engine.rootContext()->setContextProperty("fileDeleter", &fileDeleter);

    //截图
    ScreenShot screenshot;
    engine.rootContext()->setContextProperty("screenshot", &screenshot);
    // //读文件
    // LogReader logReader;
    // engine.rootContext()->setContextProperty("logReader", &logReader);


    //更新相关
    //gitUpdaterQML gitupdaterqml;
    engine.rootContext()->setContextProperty("gitupdaterqml",&gitUpdaterQML::instance());

    const QUrl url(QStringLiteral("qrc:/main.qml"));

    QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
        &app, [url](QObject *obj, const QUrl &objUrl) {
            if (!obj && url == objUrl)
                QCoreApplication::exit(-1);
        }, Qt::QueuedConnection);

    // QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
    //     &app, [url](QObject *obj, const QUrl &objUrl) {
    //         if (!obj && url == objUrl) {
    //             QCoreApplication::exit(-1);
    //         }
    //     }, Qt::QueuedConnection);
    //testHiconVMS();

    // QVector<QVector<int>> data = {{1, 4, 5}, {3, 4}, {7, 5}, {}, {2, 2, 2, 2}};
    // ChartPlotter::getInstance().drawCharts(data);

    MyRealTimeObject *myObject = new MyRealTimeObject();
    QThread *realTimeThread = new QThread();
    myObject->moveToThread(realTimeThread);

    // QObject::connect(realTimeThread, &QThread::started, [](){
    //     pthread_t threadId = pthread_self();

    //     // 设置实时调度策略和优先级
    //     struct sched_param param;
    //     param.sched_priority = 90;  // 实时优先级，范围1-99，数值越高优先级越高
    //     if (pthread_setschedparam(threadId, SCHED_FIFO, &param) != 0) {
    //         qWarning() << "Failed to set real-time scheduling policy";
    //     }else
    //         qWarning() << "Sucessufl to set real-time scheduling policy";
    // });

    QObject::connect(realTimeThread, &QThread::started, myObject, &MyRealTimeObject::start);
    realTimeThread->start();

    const QUrl url1(QStringLiteral("qrc:/main.qml"));
    engine.load(url1);
    // NetworkManager::instance()->checkForUpdates();
    // NetworkManager::instance()->getDeviceInfo();

    if(isRestart)
    {
        LogDebug << "系统重启请检查系统; restart";
        ErrorDialogManager::instance().showNonBlockingError("系统崩溃","已经正常重启，如频繁出现请联系技术人员");
    }
    PCcore::getInstance().loadModels();
//gitUpdaterQML::instance().startUpdate();
    return app.exec();
}
